<template>
	<div class="app-container">
		<template v-if="taskDetails">
			<template v-if="isSunshine">
				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button
							type="primary"
							icon="el-icon-plus"
							size="mini"
							@click="handleAdd"
						>新增</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							type="success"
							icon="el-icon-edit"
							size="mini"
							:disabled="single"
							@click="handleUpdate"
						>修改</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							type="danger"
							icon="el-icon-delete"
							size="mini"
							:disabled="multiple"
							@click="handleDelete"
						>删除</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button
							type="warning"
							icon="el-icon-download"
							size="mini"
							@click="handleExport"
						>导出</el-button>
					</el-col>
					<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
				</el-row>

				<el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column type="index" label="序号" align="center" :index="indexMethod" width="50" />
					<el-table-column label="医生姓名" align="center" prop="doctorName" />
					<el-table-column label="月份" align="center">
						<template slot-scope="scope">{{scope.row.year}}-{{scope.row.month}}</template>
					</el-table-column>
					<el-table-column label="月任务" align="center" prop="totalPoints" />
					<el-table-column label="完成情况" align="center">
						<template slot-scope="scope">{{getExecution(scope.row).completed}}</template>
					</el-table-column>
					<el-table-column label="未完成" align="center">
						<template slot-scope="scope">{{getExecution(scope.row).incomplete}}</template>
					</el-table-column>
					<el-table-column label="完成率" align="center">
						<template slot-scope="scope">{{getExecution(scope.row).completionRate}}</template>
					</el-table-column>
					<el-table-column label="是否顺延" align="center">
						<template slot-scope="scope">
							<span v-if="scope.row.isPostpone=='true'"><el-tag type="success">是</el-tag></span>
							<span v-else><el-tag type="info">否</el-tag></span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<el-button
								size="mini"
								type="text"
								icon="el-icon-edit"
								@click="viewDetails(scope.row)"
							>完成明细</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination
					v-show="total>0"
					:total="total"
					:page.sync="queryParams.pageNum"
					:limit.sync="queryParams.pageSize"
					@pagination="getList"
				/>

				<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
					<el-form ref="form" :model="form" :rules="rules" label-width="80px">
						<el-form-item label="总积分" prop="totalPoints">
							<el-input-number v-model="form.totalPoints" placeholder="请输入总积分" :step="100"
											 style="width: 70%;" controls-position="right" />
						</el-form-item>
						<el-form-item label="任务日期" prop="year">
							<el-date-picker v-model="datePicker" type="month" placeholder="选择月"
											style="width: 70%;" @change="handleDatePickerChange" :picker-options="pickerOptions"></el-date-picker>
						</el-form-item>
						<el-form-item label="是否顺延" prop="isPostpone">
							<el-switch v-model="form.isPostpone" active-color="#13ce66" :active-value="true" :inactive-value="false"></el-switch>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button type="primary" @click="submitForm">确 定</el-button>
						<el-button @click="cancel">取 消</el-button>
					</div>
				</el-dialog>
			</template>
			<template v-else>
				<el-empty description="该医生还不是签约医生，如想设置任务请先签约"></el-empty>
			</template>
		</template>
		<template v-else>
			<el-page-header @back="goBack" content="任务列表" />
			<div style="margin-top: 20px;">
				<el-form ref="elForm" :inline="true" label-width="80px">
					<el-row :gutter="10">
						<el-col :span="8">
							<el-form-item label="任务月份">{{currentTask.year}}-{{currentTask.month}}</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="任务目标">{{ getExecution(currentTask).completed }}/{{ currentTask.totalPoints }}</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="完成率">{{ getExecution(currentTask).completionRate }}</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-table :data="pointEvents" style="width: 100%">
					<el-table-column type="index" label="序号" align="center" width="50" />
					<el-table-column label="任务名称" align="center" prop="pointEventName" />
					<el-table-column label="任务积分" align="center" prop="pointEventValue" />
					<el-table-column label="发生时间" align="center">
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</template>
	</div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, exportTask } from "@/api/doctor/task";
import dayjs from 'dayjs'

export default {
	name: "Task",
	props: {
		doctorId: {},
		sunshine: {}
	},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			taskList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				doctorId: null,
				totalPoints: null,
				isPostpone: null,
				year: null,
				month: null,
				pointIntegral: null,
				pointEventName: null,
				count: null
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				year: [
					{required: true, message: '请选择任务日期', trigger: 'change'}
				],
				totalPoints: [
					{required: true, message: '请填写任务上限', trigger: 'change'}
				],
				isPostpone: [
					{required: true, message: '请设置是否顺延', trigger: 'change'}
				]
			},
			datePicker: '',
			pickerOptions: {
				disabledDate(time) {
					return time.getTime() < Date.now() - 8.64e7;
				}
			},
			taskDetails: true,
			pointEvents: [],
			currentTask: {},
			isSunshine: false
		};
	},
	methods: {
		getList() {
			this.loading = true;
			listTask(this.queryParams).then(response => {
				this.taskList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				doctorTaskId: null,
				doctorId: null,
				totalPoints: null,
				isPostpone: null,
				year: null,
				month: null,
				createBy: null,
				createTime: null,
				updateTime: null,
				updateBy: null,
				pointIntegral: null,
				pointEventName: null,
				count: null
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.doctorTaskId)
			this.single = selection.length!==1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.form.isPostpone = true;
			this.title = "定制任务";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const doctorTaskId = row.doctorTaskId || this.ids
			getTask(doctorTaskId).then(response => {
				this.form = response.data;
				this.datePicker = dayjs().year(this.form.year).month(this.form.month - 1);
				this.form.isPostpone = this.form.isPostpone == 'true';
				this.open = true;
				this.title = "修改任务";
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					this.form.doctorId = this.doctorId;
					if (this.form.doctorTaskId != null) {
						updateTask(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							}
						});
					} else {
						addTask(this.form).then(response => {
							if (response.code === 200) {
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							}
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const doctorTaskIds = row.doctorTaskId || this.ids;
			this.$confirm('是否确认删除【任务】编号为"' + doctorTaskIds + '"的数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function() {
				return delTask(doctorTaskIds);
			}).then(() => {
				this.getList();
				this.msgSuccess("删除成功");
			}).catch(function() {});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有【任务】数据项?', "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(function() {
				return exportTask(queryParams);
			}).then(response => {
				this.download(response.msg);
			}).catch(function() {});
		},
		indexMethod(index) {
			return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
		},
		handleDatePickerChange(val) {
			this.form.month = dayjs(val).month() + 1;
			this.form.year = dayjs(val).year();
		},
		getExecution(task) {
			let events = task.pointEvents;
			let points = [];
			for (let i = 0; i < events.length; i++) {
				points.push(Number(events[i].pointEventValue));
			}
			let completed = points.length > 0 ? points.reduce((a,b) => a + b): 0;
			return { completed: completed, incomplete: task.totalPoints - completed, completionRate: ((completed / task.totalPoints) * 100).toFixed(2) + '%' }
		},
		viewDetails(task) {
			this.currentTask = task;
			this.pointEvents = task.pointEvents;
			this.taskDetails = false;
		},
		goBack() {
			this.taskDetails = true;
		}
	},
	watch: {
		doctorId: function() {
			this.queryParams.doctorId = this.doctorId
			this.getList();
		},
		sunshine: function() {
			this.isSunshine = this.sunshine == 1;
		}
	}
};
</script>
